package cn.tedu.charging.order.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * EMQX的消息中间的发送者
 * 订单服务 给 设备发送 消息(指令)
 */
@Component
@Slf4j
public class MqttProducer {
    @Autowired
    private MqttClient mqttClient;

    /**
     * 通过 MqttConfiguration类中 @Bean注解创建的 MqttClient
     * 给EMQX消息中间件
     * 发送消息
     */
    public Boolean send(String topic, String message) {
        Boolean success = false;
        try {
            mqttClient.publish(topic, message.getBytes(), 0, true);
            success = true;
        } catch (MqttException e) {
            // 接入告警系统 1秒钟超过3次失败 告警
            log.error("MqttProducer.send() 发送消息失败: {},消息：{}",topic, message);
        }
        return success;
    }

}
